<?php

namespace App\Http\Controllers;

use App\WechatHandlers\EventMessageHandler;
use App\WechatHandlers\ImageMessageHandler;
use App\WechatHandlers\TextMessageHandler;
use EasyWeChat\Kernel\Messages\Message;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Http\Common\Consumer;
use App\Models\Text;
use App\Models\ReplyText;
use App\Models\Subscribe;
use App\Models\Click;
use Overtrue\LaravelWeChat\Facade as EasyWechat;


class WechatController extends Controller
{
    /**
     * 微信服务器事件推送处理
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\BadRequestException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \ReflectionException
     */
    public function server()
    {
        $app = EasyWechat::officialAccount();
        // 文本消息处理
        $app->server->push(TextMessageHandler::class, Message::TEXT);
        // 事件消息处理
        $app->server->push(EventMessageHandler::class, Message::EVENT);
        // 图片消息处理
        $app->server->push(ImageMessageHandler::class, Message::IMAGE);

        return $app->server->serve();
    }


    /**
     * 开发者模式下，接收微信事件
     */
    public function api(Request $request)
    {
        /*开启开发者模式*/
//        $res = $request->all();
//        $nonce     = $res['nonce'];
////        $token     = 'wash_technology';//Token(蓝月亮洗涤科技)
//        $token     = 'moon_home';//Token(月亮之家)
//        $timestamp = $res['timestamp'];
//        $echostr   = $res['echostr'];
//        $signature = $res['signature'];
//        //形成数组，然后按字典序排序
//        $array = array($nonce, $timestamp, $token);
//        sort($array);
//        //拼接成字符串,sha1加密 ，然后与signature进行校验
//        $str = sha1(implode($array));
//
//        if($str == $signature && $echostr){
//            echo $echostr;
//        }

        /*接收xml数据*/
        $res = file_get_contents("php://input");
        LOG::debug($res);

        //调用消息处理
        $this->reponse_msg($res);
    }

    /**
     * 设置消息处理
     * $postArr 接收到的数据(xml格式)
     *
     * @param string $postArr 接收到的数据(xml格式)
     */
    public function reponse_msg($postArr = ''){
        $Comsumer = new Consumer();
        //1.获取到微信返回过来的post数据$postArr(xml格式)
        /*内容格式
        <xml>
            <ToUserName><![CDATA[toUser]]></ToUserName>
            <FromUserName><![CDATA[FromUser]]></FromUserName>
            <CreateTime>123456789</CreateTime>
            <MsgType><![CDATA[event]]></MsgType>
            <Event><![CDATA[subscribe]]></Event>
            <EventKey><![CDATA[EVENTKEY]]></EventKey>
        </xml>
        */
        //2.处理消息类型，并设置回复类型和内容
        $postObj = simplexml_load_string($postArr);
        /*解析后的格式
        $postObj->ToUserName = '';
        $postObj->FromUserName = '';
        $postObj->CreateTime = '';
        $postObj->MsgType = '';
        $postObj->Event = '';
        $postObj->EventKey = '';
        */
        //判断该数据包是否是事件推送
        if (strtolower($postObj->MsgType) == 'event'){
            if(strtolower($postObj->Event) == 'subscribe'){//如果是关注subscribe事件
                $toUser   = $postObj->FromUserName;
                $fromUser = $postObj->ToUserName;
                $time     = time();

                //查询文本消息表
                $Subscribe = Subscribe::where(array('status'=>1))->select('reply_type','msg_id')->first();
                if($Subscribe){
                    $reply_type = $Subscribe['reply_type'];
                    $msg_id = $Subscribe['msg_id'];

                    /*当回复为文本消息时*/
                    if($reply_type == 'text'){
                        $ReplyText = ReplyText::where(array('id' => $msg_id))->select('content')->first();
                        if($ReplyText){
                            $content = $ReplyText['content'];
                        }
                    }
                }

                $Comsumer->return_content($toUser,$fromUser,$time,$content);//调用回复文本消息函数
            }else if(strtolower($postObj->Event) == 'click'){//如果是点击自定义菜单click事件
                $toUser   = $postObj->FromUserName;
                $fromUser = $postObj->ToUserName;
                $time     = time();

                $EventKey = strtolower($postObj->EventKey);
                //查询点击表
                $Click = Click::where(array('key'=>$EventKey))->select('reply_type','msg_id')->first();
                if($Click){
                    $reply_type = $Click['reply_type'];
                    $msg_id = $Click['msg_id'];

                    /*当回复为文本消息时*/
                    if($reply_type == 'text'){
                        $ReplyText = ReplyText::where(array('id' => $msg_id))->select('content')->first();
                        if($ReplyText){
                            $content = $ReplyText['content'];
                        }
                    }
                }

                $Comsumer->return_content($toUser,$fromUser,$time,$content);//调用回复文本消息函数
            }
        }else if(strtolower($postObj->MsgType) == 'text'){//当该数据包为接收普通消息时
            $toUser   = $postObj->FromUserName;
            $fromUser = $postObj->ToUserName;
            $time     = time();
            //查询文本消息表
            $Text = Text::where(array('text' => strtolower($postObj->Content), 'status'=>1))->select('reply_type','msg_id')->first();
            if($Text){
                $reply_type = $Text['reply_type'];
                $msg_id = $Text['msg_id'];

                /*当回复为文本消息时*/
                if($reply_type == 'text'){
                    $ReplyText = ReplyText::where(array('id' => $msg_id))->select('content')->first();
                    if($ReplyText){
                        $content = $ReplyText['content'];
                    }else{
                        $content = "您输入的请求我看不懂呢，请联系客服吧~O(∩_∩)O";
                    }
                }else{
                    $content = "您输入的请求我看不懂呢，请联系客服吧~O(∩_∩)O";
                }
            }else{
                $content = "您输入的请求我看不懂呢，请联系客服吧~O(∩_∩)O";
            }

            $Comsumer->return_content($toUser,$fromUser,$time,$content);//调用回复文本消息函数
        }
    }
}
